import { ref, reactive } from 'vue'
import axios, { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import md5 from 'md5'

// import api from '@/api/index'
import base from '@/utils/utils'

// vue 实例获取方式
export const loginFormRef = ref(null)

export let loading = ref<boolean>(false)

// 登录信息类型
interface LoginInfo {
  username: string
  password: string
  vcode: string
  sessionId: string
  identifyUrl: string
}
// 实际登录入参类型
interface ParamsTypes {
  account: string
  password?: string
  code: string
  sessionId: string
}

// 验证规则类型
interface loginRules {
  username: {
    required: boolean
    message: string
    trigger: string
  }[]
  password: {
    required: boolean
    message: string
    trigger: string
  }[]
  vcode: {
    required: boolean
    message: string
    trigger: string
  }[]
}

export const loginForm = reactive<LoginInfo>({
  username: 'zhanglei',
  password: 'ZHANG840@test',
  vcode: '',
  sessionId: '',
  identifyUrl: ''
})

// 校验规则
export const loginRules = reactive<loginRules>({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  vcode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
})
 // 验证码获取地址
 export const refreshIdentify = () => {
  loginForm.sessionId = base.randomString(32)
  loginForm.identifyUrl = `/api/getCheckCode.jpg?sessionId=${loginForm.sessionId}`
}
// 触发登录方法
export const submitForm = () => {
  const newLoginFormRef = loginFormRef as any
  const validate = newLoginFormRef.value.validate
  validate((valid: boolean) => {
    if (valid) {
      base.throttle(handleLogin(newLoginFormRef.value), 3000)
    } else {
      console.log('submit error')
      return false
    }
  })
}

// 登录接口请求
export const handleLogin = async (vm: { $router: { name: string }[] }) => { 
  const params: ParamsTypes = {
    account: loginForm.username,
    password: `${base.randomString(3)}${md5(loginForm.password)}${base.randomString(3)}`,
    code: loginForm.vcode,
    sessionId: loginForm.sessionId
  }
  axios({
    url: '/api/pcLogin',
    method: 'post',
    data: qs.stringify(params),
    timeout: 5 * 1000,
    withCredentials: true
  }).then((res: AxiosResponse<any>) => {
    loading.value = true
    if (res.status === 200) {
      if (res.data.code === 0) {
        ElMessage.success('登录成功!')
        const { token } = res.data.result
        base.setSessionStorage('token', token.token)
        loading.value = false
        // vm.$router.push({name: 'Home'})
        window.location.href = '/'
      } else {
        ElMessage.closeAll()
        ElMessage.error(res.data.msg)
        loading.value = false
        refreshIdentify()
      }
    }
  }).catch((error) => {
    console.log(error)
    loading.value = false
  })
}
